import React, { FC, useState } from "react";
import { Button, Modal, Upload, message, UploadProps, GetProp } from "antd";
import styles from "./styles.less";
import Https from "@/utils/Https";
import {
  CloudUploadOutlined,
  CloudDownloadOutlined,
  InboxOutlined,
  RightOutlined,
} from "@ant-design/icons";
interface propType {
  downUrl: string; //下载模板的URL
  uploadUrl: string; //上传文件的URL
  title: string; //弹窗的标题
  onSuccess: () => void; //上传成功的回调事件
  onClose: () => void; //关闭弹窗的回调事件
}
type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];
const ExportFile: FC<propType> = (props) => {
  const { downUrl, uploadUrl, title, onSuccess, onClose } = props;
  const [xlsList, setXlsList] = useState([]);
  const [loading, setLoading] = useState<boolean>(false);
  //定义uploadprops格式
  const uploadprops: UploadProps = {
    name: "file",
    accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    maxCount: 1,
    fileList: xlsList,
    beforeUpload: (file) => {
      setXlsList([file]);
      return false;
    },
    // onChange(info) {
    //   console.log(info, "__info");
    //   if (info.file.status !== "uploading") {
    //     console.log(info.file, info.fileList);
    //   }
    //   if (info.file.status === "done") {
    //     setXlsList(info.file.originFileObj);
    //   } else if (info.file.status === "error") {
    //     message.error(`${info.file.name}文件上传失败`);
    //   } else if (info.file.status == "removed") {
    //     setXlsList("");
    //   }
    // },
    // beforeUpload: (file) => {
    //   return false;
    //   return new Promise((resolve, reject) => {
    //     if (file.name.indexOf("xlsx") > -1 || file.name.indexOf("xls") > -1) {
    //       resolve(true);
    //     } else {
    //       message.error("请上传.xls,.xlsx格式的文件");
    //       return false;
    //     }
    //   });
    // },
  };
  //上传文件
  const uploadTemplate = async () => {
    setLoading(true);
    const formData = new FormData();
    formData.append("file", xlsList[0] as FileType);
    let data = formData;
    let res = await Https.postdownload(uploadUrl, data, true);
    setLoading(false);
    if (res.size > 0) {
      if (res.type == "application/json") {
        res
          .text()
          .then(function (text) {
            // 将文本转换为JSON对象
            var jsonData = JSON.parse(text);
            console.log(jsonData); // 输出转换后的JSON对象
            message.error(jsonData.msg || "");
          })
          .catch(function (error) {
            message.error("解析错误");
          });
      } else {
        const blob = new Blob([res]);
        let downName =
          xlsList && xlsList.length > 0 ? xlsList[0].name.split(".")[0] : "";
        let fileName = downName + new Date().getTime() + ".xlsx";
        if ("msSaveOrOpenBlob" in navigator) {
          window.navigator.msSaveOrOpenBlob(blob, fileName);
        } else {
          const dom = document.createElement("a");
          const downUrl = window.URL.createObjectURL(blob);
          dom.href = downUrl;
          dom.download = fileName;
          dom.style.display = "none";
          document.body.appendChild(dom);
          dom.click();
          dom.parentNode.removeChild(dom);
          window.URL.revokeObjectURL(downUrl);
        }
        message.error("上传文件报错");
      }
    } else {
      message.success("上传成功");
      //上传成功
      onSuccess && onSuccess();
    }
  };
  //下载模板文件
  const importTemplate = async () => {
    let params = {
      responseType: "blob",
    };
    let res = await Https.post(downUrl, params);
    let url = window.URL.createObjectURL(res.data);
    let a = document.createElement("a");
    document.body.appendChild(a);
    let fileName = res.headers["download-filename"];
    a.href = url;
    a.download = title + ".xlsx";
    a.click();
    window.URL.revokeObjectURL(url);
  };
  //关闭弹窗
  const handleCancel = () => {
    onClose();
  };
  return (
    <Modal
      title={title}
      open={true}
      onCancel={handleCancel}
      confirmLoading={loading}
      width={800}
      onOk={() => {
        if (xlsList.length == 0) {
          message.warning("请上传文件!");
        } else {
          uploadTemplate();
        }
      }}
    >
      <div>
        <div className={styles.steps}>
          <div className={styles.item}>
            <InboxOutlined style={{ fontSize: "80px" }} />
            <div className={styles.item_text}>下载模版</div>
          </div>
          <div className={styles.item}>
            <InboxOutlined style={{ fontSize: "80px" }} />
            <div className={styles.item_text}>上传数据文件</div>
          </div>
          <div className={styles.tips}>按模板要求录入数据</div>
          <div className={styles.tipsIcon}>
            <RightOutlined style={{ fontSize: "30px", color: "#1f77f2" }} />
          </div>
        </div>

        <div className={styles.downBox}>
          <div className={styles.box_item}>
            <div className={styles.icon}>
              <CloudDownloadOutlined
                style={{ fontSize: "40px", color: "#a9a4a4" }}
              />
            </div>
            <span style={{ marginLeft: "20px", fontSize: "16px" }}>
              下载模版
            </span>
          </div>
          <div className={styles.box_item}>
            <Button
              type="link"
              icon={
                <CloudDownloadOutlined
                  style={{ fontSize: "26px", color: "#a9a4a4" }}
                />
              }
              onClick={importTemplate}
            >
              点此下载
            </Button>
          </div>
        </div>

        <div className={styles.uploadBox}>
          <div className={styles.box_item}>
            <div className={styles.icon}>
              <CloudUploadOutlined
                style={{ fontSize: "40px", color: "#a9a4a4" }}
              />
            </div>
            <div style={{ marginLeft: "20px", marginTop: "40px" }}>
              <span style={{ fontSize: "16px" }}>上传文件</span>
              <p style={{ marginTop: 10, fontSize: "16px", color: "#a9a4a4" }}>
                支持扩展名:.xls .xlsx
              </p>
            </div>
          </div>
          <div className={styles.box_item}>
            <Upload {...uploadprops}>
              <Button
                type="link"
                icon={
                  <CloudUploadOutlined
                    style={{ fontSize: "26px", color: "#a9a4a4" }}
                  />
                }
              >
                点此上传
              </Button>
            </Upload>
            <div className={styles.fileTips}>
              {xlsList.length > 0 && xlsList[0].name}
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default ExportFile;
